package com.kedacom.demo.modb.weibo.service;

import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.kedacom.demo.modb.rabbitmq.gateway.ModbMessageGateway;
import com.kedacom.demo.modb.rabbitmq.message.UpdateAccountSqlAndEventMessage;
import com.kedacom.demo.modb.weibo.dao.TsoAccountDao;
import com.kedacom.demo.modb.weibo.model.Account;

/**
 * 用户帐号管理实现
 * @author luocanfeng
 * @date 2013-1-14
 */
@Transactional
@Service("accountService")
public class AccountServiceImpl implements AccountService {

	private Logger logger = LoggerFactory.getLogger(getClass());

	@Value("#{rabbitmq['rabbitmq.routingkey.sqlevent.topublic']}")
	private String routingKeyToPubilcSqlEvent;

	@Resource(name = "apJdbcDaoSupport")
	private JdbcDaoSupport apJdbcDaoSupport;

	@Resource
	private TsoAccountDao tsoAccountDao;

	@Resource
	private ModbMessageGateway modbMessageGateway;

	@Override
	public List<Account> listAll() {
		return tsoAccountDao.listAll();
	}

	private String modifyBriefSql = "update account set brief=? where moid=?";

	@Override
	public void modifyBrief(String moid, String brief) {
		// TODO MoDB方案缺陷一：业务方法需要清楚持久化（sql）细节
		Object[] sqlArgs = new Object[] {
				brief, moid
		};
		// persist to db
		apJdbcDaoSupport.getJdbcTemplate().update(modifyBriefSql, sqlArgs);
		logger.debug("Persisted to apdb.");
		tsoAccountDao.modifyBrief(moid, brief);
		logger.debug("Persisted to tsodb.");

		UpdateAccountSqlAndEventMessage message = new UpdateAccountSqlAndEventMessage(moid, modifyBriefSql, sqlArgs);
		modbMessageGateway.sendModbMessage(routingKeyToPubilcSqlEvent, message);
		logger.debug("Sent SqlAndEvent to public: {}",
				ToStringBuilder.reflectionToString(message, ToStringStyle.SHORT_PREFIX_STYLE));
	}

	@Override
	public Account getByMoid(String moid) {
		return tsoAccountDao.getByMoid(moid);
	}

}
